package org.example.user;

import org.example.AbstractWebMvcApplicationInitializer;
import org.example.user.context.ComponentContext;
import org.example.user.projects.dao.DBConnectManager;
import org.example.user.projects.dao.DbUtil;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;

/**
 * Web-Mvc应用启动类
 *
 * @author hrz
 * @since 2021/3/3 0003
 */
public class WebMvcApplicationInitializer extends AbstractWebMvcApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        // 初始化组件上下文
        try {
            ComponentContext componentContext = new ComponentContext();
            componentContext.init(servletContext);

            // 初始化ORM相关处理
            DBConnectManager dbConnectManager = componentContext.lookComponent("jdbc/DBConnectManager");
            dbConnectManager.init(componentContext.lookComponent("jdbc/DataSource"));
            DbUtil.setDBConnectManager(dbConnectManager);

        } catch (Throwable t) {
            throw new ServletException("初始化组件上下文失败："+t.getMessage(), t);
        }

        // 避免在初始化controller时，从组件上下文获取service组件报错，所以放在初始化组件上下文之后执行。
        super.onStartup(servletContext);
    }

    @Override
    public String basePackage() {
        return "org.example.user";
    }

}
